package com.dpj.noLock.atomic;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

@Slf4j(topic = "c.AtomicStampedReferenceDemo")
public class AtomicStampedReferenceDemo {
    //ABA 问题
    static AtomicStampedReference<String> ref=new AtomicStampedReference<>("A",0);
    public static void main(String[] args) throws InterruptedException {
        log.debug("main test");
        //获取值A
        String prev = ref.getReference();
        //获取版本号
        int stamp = ref.getStamp();
        log.debug("{}",stamp);
        System.out.println(prev);
        other();
        Thread.sleep(1000);

        //尝试改为c
        log.debug("change A-C {}",ref.compareAndSet(prev,"c",stamp,stamp+1));
    }
    private static void other() throws InterruptedException {
        new Thread(()->{
            int stamp = ref.getStamp();
            log.debug("change A->B {}",ref.compareAndSet(ref.getReference(), "B",stamp,stamp+1));
        },"t1").start();
        Thread.sleep(10);
        new Thread(()->{
            int stamp = ref.getStamp();
            log.debug("change B-A {}",ref.compareAndSet(ref.getReference(),"A",stamp,stamp+1));
        },"t2").start();
    }

}
